<template>
  <div class="error-book">
    <div class="container">
      <h1>错题本</h1>
      
      <!-- 功能选择区域 -->
      <div class="function-tabs">
        <button 
          :class="['tab-btn', { active: activeTab === 'camera' }]"
          @click="activeTab = 'camera'"
        >
          📷 拍照记录
        </button>
        <button 
          :class="['tab-btn', { active: activeTab === 'draw' }]"
          @click="activeTab = 'draw'"
        >
          ✏️ 手绘记录
        </button>
        <button 
          :class="['tab-btn', { active: activeTab === 'text' }]"
          @click="activeTab = 'text'"
        >
          📝 文字记录
        </button>
      </div>

      <!-- 拍照功能 -->
      <div v-if="activeTab === 'camera'" class="camera-section">
        <div class="camera-container">
          <video ref="video" class="camera-preview" autoplay></video>
          <canvas ref="canvas" class="camera-canvas" style="display: none;"></canvas>
        </div>
        <div class="camera-controls">
          <button @click="startCamera" :disabled="isCameraActive">开启摄像头</button>
          <button @click="takePhoto" :disabled="!isCameraActive">拍照</button>
          <button @click="stopCamera" :disabled="!isCameraActive">关闭摄像头</button>
        </div>
        <div v-if="capturedImage" class="captured-image">
          <img :src="capturedImage" alt="拍摄的错题" />
          <div class="image-actions">
            <input v-model="photoTitle" placeholder="输入错题标题" class="title-input" />
            <textarea v-model="photoDescription" placeholder="输入错题描述" class="description-input"></textarea>
            <button @click="savePhoto">保存错题</button>
            <button @click="capturedImage = null">重新拍摄</button>
          </div>
        </div>
      </div>

      <!-- 手绘功能 -->
      <div v-if="activeTab === 'draw'" class="draw-section">
        <div class="draw-container">
          <canvas ref="drawCanvas" class="draw-canvas"></canvas>
        </div>
        <div class="draw-controls">
          <div class="color-picker">
            <label>颜色:</label>
            <input type="color" v-model="drawColor" />
          </div>
          <div class="brush-size">
            <label>画笔大小:</label>
            <input type="range" v-model="brushSize" min="1" max="20" />
            <span>{{ brushSize }}px</span>
          </div>
          <button @click="clearCanvas">清空画布</button>
          <button @click="saveDrawing">保存手绘</button>
        </div>
        <div class="draw-info">
          <input v-model="drawTitle" placeholder="输入错题标题" class="title-input" />
          <textarea v-model="drawDescription" placeholder="输入错题描述" class="description-input"></textarea>
        </div>
      </div>

      <!-- 文字记录功能 -->
      <div v-if="activeTab === 'text'" class="text-section">
        <div class="text-input-container">
          <input v-model="textTitle" placeholder="输入错题标题" class="title-input" />
          <textarea 
            v-model="textContent" 
            placeholder="请输入错题内容..." 
            class="content-textarea"
            rows="10"
          ></textarea>
          <div class="text-actions">
            <button @click="saveText">保存文字记录</button>
            <button @click="clearText">清空内容</button>
          </div>
        </div>
      </div>

      <!-- 错题列表 -->
      <div class="error-list">
        <h2>我的错题本</h2>
        <div v-if="errorItems.length === 0" class="empty-state">
          <p>还没有错题记录，开始记录你的第一个错题吧！</p>
        </div>
        <div v-else class="error-items">
          <div 
            v-for="(item, index) in errorItems" 
            :key="index" 
            class="error-item"
            @click="viewErrorItem(item)"
          >
            <div class="item-header">
              <h3>{{ item.title || '未命名错题' }}</h3>
              <span class="item-type">{{ getTypeLabel(item.type) }}</span>
              <span class="item-date">{{ formatDate(item.date) }}</span>
            </div>
            <div class="item-content">
              <div v-if="item.type === 'photo'" class="photo-preview">
                <img :src="item.image" alt="错题图片" />
              </div>
              <div v-else-if="item.type === 'draw'" class="draw-preview">
                <img :src="item.image" alt="手绘错题" />
              </div>
              <div v-else class="text-preview">
                <p>{{ truncateText(item.content, 100) }}</p>
              </div>
            </div>
            <div v-if="item.description" class="item-description">
              <p>{{ item.description }}</p>
            </div>
            <div class="item-actions">
              <button @click.stop="deleteErrorItem(index)" class="delete-btn">删除</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 查看错题详情模态框 -->
    <div v-if="selectedItem" class="modal-overlay" @click="selectedItem = null">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ selectedItem.title || '未命名错题' }}</h3>
          <button @click="selectedItem = null" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div v-if="selectedItem.type === 'photo' || selectedItem.type === 'draw'" class="modal-image">
            <img :src="selectedItem.image" alt="错题图片" />
          </div>
          <div v-if="selectedItem.content" class="modal-text">
            <p>{{ selectedItem.content }}</p>
          </div>
          <div v-if="selectedItem.description" class="modal-description">
            <h4>描述:</h4>
            <p>{{ selectedItem.description }}</p>
          </div>
          <div class="modal-date">
            <p>创建时间: {{ formatDate(selectedItem.date) }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ErrorBook',
  data() {
    return {
      activeTab: 'camera',
      isCameraActive: false,
      capturedImage: null,
      photoTitle: '',
      photoDescription: '',
      
      // 手绘相关
      drawColor: '#000000',
      brushSize: 5,
      isDrawing: false,
      drawTitle: '',
      drawDescription: '',
      
      // 文字相关
      textTitle: '',
      textContent: '',
      
      // 错题列表
      errorItems: [],
      selectedItem: null
    }
  },
  mounted() {
    this.loadErrorItems()
    this.initDrawCanvas()
  },
  methods: {
    // 摄像头功能
    async startCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ 
          video: { facingMode: 'environment' } 
        })
        this.$refs.video.srcObject = stream
        this.isCameraActive = true
      } catch (error) {
        alert('无法访问摄像头: ' + error.message)
      }
    },
    
    takePhoto() {
      const video = this.$refs.video
      const canvas = this.$refs.canvas
      const context = canvas.getContext('2d')
      
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      context.drawImage(video, 0, 0)
      
      this.capturedImage = canvas.toDataURL('image/jpeg')
    },
    
    stopCamera() {
      const video = this.$refs.video
      if (video.srcObject) {
        video.srcObject.getTracks().forEach(track => track.stop())
        video.srcObject = null
      }
      this.isCameraActive = false
    },
    
    savePhoto() {
      if (!this.capturedImage) return
      
      const errorItem = {
        type: 'photo',
        title: this.photoTitle,
        description: this.photoDescription,
        image: this.capturedImage,
        date: new Date()
      }
      
      this.errorItems.unshift(errorItem)
      this.saveErrorItems()
      
      // 重置表单
      this.capturedImage = null
      this.photoTitle = ''
      this.photoDescription = ''
      
      alert('错题保存成功！')
    },
    
    // 手绘功能
    initDrawCanvas() {
      const canvas = this.$refs.drawCanvas
      if (!canvas) return
      
      canvas.width = 600
      canvas.height = 400
      const ctx = canvas.getContext('2d')
      
      // 设置画布背景
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      
      // 鼠标事件
      canvas.addEventListener('mousedown', this.startDrawing)
      canvas.addEventListener('mousemove', this.draw)
      canvas.addEventListener('mouseup', this.stopDrawing)
      canvas.addEventListener('mouseout', this.stopDrawing)
      
      // 触摸事件（移动端支持）
      canvas.addEventListener('touchstart', this.handleTouchStart)
      canvas.addEventListener('touchmove', this.handleTouchMove)
      canvas.addEventListener('touchend', this.stopDrawing)
    },
    
    startDrawing(e) {
      this.isDrawing = true
      this.draw(e)
    },
    
    draw(e) {
      if (!this.isDrawing) return
      
      const canvas = this.$refs.drawCanvas
      const ctx = canvas.getContext('2d')
      const rect = canvas.getBoundingClientRect()
      const x = e.clientX - rect.left
      const y = e.clientY - rect.top
      
      ctx.lineWidth = this.brushSize
      ctx.lineCap = 'round'
      ctx.strokeStyle = this.drawColor
      
      ctx.lineTo(x, y)
      ctx.stroke()
      ctx.beginPath()
      ctx.moveTo(x, y)
    },
    
    stopDrawing() {
      this.isDrawing = false
      const canvas = this.$refs.drawCanvas
      const ctx = canvas.getContext('2d')
      ctx.beginPath()
    },
    
    handleTouchStart(e) {
      e.preventDefault()
      const touch = e.touches[0]
      const mouseEvent = new MouseEvent('mousedown', {
        clientX: touch.clientX,
        clientY: touch.clientY
      })
      this.startDrawing(mouseEvent)
    },
    
    handleTouchMove(e) {
      e.preventDefault()
      const touch = e.touches[0]
      const mouseEvent = new MouseEvent('mousemove', {
        clientX: touch.clientX,
        clientY: touch.clientY
      })
      this.draw(mouseEvent)
    },
    
    clearCanvas() {
      const canvas = this.$refs.drawCanvas
      const ctx = canvas.getContext('2d')
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
    },
    
    saveDrawing() {
      const canvas = this.$refs.drawCanvas
      const imageData = canvas.toDataURL('image/png')
      
      const errorItem = {
        type: 'draw',
        title: this.drawTitle,
        description: this.drawDescription,
        image: imageData,
        date: new Date()
      }
      
      this.errorItems.unshift(errorItem)
      this.saveErrorItems()
      
      // 重置表单
      this.drawTitle = ''
      this.drawDescription = ''
      this.clearCanvas()
      
      alert('手绘错题保存成功！')
    },
    
    // 文字记录功能
    saveText() {
      if (!this.textContent.trim()) {
        alert('请输入错题内容')
        return
      }
      
      const errorItem = {
        type: 'text',
        title: this.textTitle,
        content: this.textContent,
        date: new Date()
      }
      
      this.errorItems.unshift(errorItem)
      this.saveErrorItems()
      
      // 重置表单
      this.textTitle = ''
      this.textContent = ''
      
      alert('文字错题保存成功！')
    },
    
    clearText() {
      this.textTitle = ''
      this.textContent = ''
    },
    
    // 错题管理
    loadErrorItems() {
      const saved = localStorage.getItem('errorItems')
      if (saved) {
        this.errorItems = JSON.parse(saved)
      }
    },
    
    saveErrorItems() {
      localStorage.setItem('errorItems', JSON.stringify(this.errorItems))
    },
    
    deleteErrorItem(index) {
      if (confirm('确定要删除这个错题吗？')) {
        this.errorItems.splice(index, 1)
        this.saveErrorItems()
      }
    },
    
    viewErrorItem(item) {
      this.selectedItem = item
    },
    
    getTypeLabel(type) {
      const labels = {
        photo: '📷 拍照',
        draw: '✏️ 手绘',
        text: '📝 文字'
      }
      return labels[type] || '未知'
    },
    
    formatDate(date) {
      return new Date(date).toLocaleString('zh-CN')
    },
    
    truncateText(text, length) {
      if (text.length <= length) return text
      return text.substring(0, length) + '...'
    }
  },
  
  beforeUnmount() {
    this.stopCamera()
  }
}
</script>

<style scoped>
.error-book {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.container h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.function-tabs {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 30px;
}

.tab-btn {
  padding: 12px 24px;
  border: 2px solid #007bff;
  background: white;
  color: #007bff;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.tab-btn.active {
  background: #007bff;
  color: white;
}

.tab-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
}

/* 摄像头功能样式 */
.camera-section {
  text-align: center;
}

.camera-container {
  margin-bottom: 20px;
}

.camera-preview {
  width: 100%;
  max-width: 500px;
  height: 300px;
  border: 2px solid #ddd;
  border-radius: 8px;
  background: #f0f0f0;
}

.camera-controls {
  margin-bottom: 20px;
}

.camera-controls button {
  margin: 0 10px;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background: #007bff;
  color: white;
  cursor: pointer;
}

.camera-controls button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.captured-image {
  margin-top: 20px;
}

.captured-image img {
  max-width: 100%;
  max-height: 300px;
  border: 2px solid #ddd;
  border-radius: 8px;
}

.image-actions {
  margin-top: 15px;
}

/* 手绘功能样式 */
.draw-section {
  text-align: center;
}

.draw-container {
  margin-bottom: 20px;
}

.draw-canvas {
  border: 2px solid #ddd;
  border-radius: 8px;
  background: white;
  cursor: crosshair;
}

.draw-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.color-picker, .brush-size {
  display: flex;
  align-items: center;
  gap: 10px;
}

.draw-controls button {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  background: #28a745;
  color: white;
  cursor: pointer;
}

.draw-info {
  margin-top: 20px;
}

/* 文字记录功能样式 */
.text-section {
  max-width: 800px;
  margin: 0 auto;
}

.text-input-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.content-textarea {
  width: 100%;
  padding: 15px;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  resize: vertical;
  min-height: 200px;
}

.text-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.text-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.text-actions button:first-child {
  background: #28a745;
  color: white;
}

.text-actions button:last-child {
  background: #6c757d;
  color: white;
}

/* 通用输入样式 */
.title-input {
  width: 100%;
  padding: 10px;
  border: 2px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
}

.description-input {
  width: 100%;
  padding: 10px;
  border: 2px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  resize: vertical;
  min-height: 80px;
}

/* 错题列表样式 */
.error-list {
  margin-top: 50px;
}

.error-list h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.empty-state {
  text-align: center;
  color: #666;
  padding: 40px;
}

.error-items {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.error-item {
  border: 2px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.error-item:hover {
  border-color: #007bff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.item-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.item-type {
  background: #007bff;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.item-date {
  color: #666;
  font-size: 12px;
}

.item-content {
  margin-bottom: 10px;
}

.photo-preview img, .draw-preview img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 5px;
}

.text-preview p {
  color: #666;
  margin: 0;
  line-height: 1.4;
}

.item-description {
  margin-bottom: 10px;
}

.item-description p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.item-actions {
  text-align: right;
}

.delete-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  background: #dc3545;
  color: white;
  cursor: pointer;
  font-size: 12px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  max-width: 90%;
  max-height: 90%;
  overflow-y: auto;
  position: relative;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ddd;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-image img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 5px;
  margin-bottom: 15px;
}

.modal-text p {
  color: #333;
  line-height: 1.6;
  margin-bottom: 15px;
}

.modal-description h4 {
  color: #333;
  margin-bottom: 5px;
}

.modal-description p {
  color: #666;
  line-height: 1.4;
}

.modal-date p {
  color: #999;
  font-size: 14px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .function-tabs {
    flex-direction: column;
    align-items: center;
  }
  
  .tab-btn {
    width: 200px;
  }
  
  .draw-controls {
    flex-direction: column;
    gap: 10px;
  }
  
  .error-items {
    grid-template-columns: 1fr;
  }
  
  .camera-preview {
    height: 200px;
  }
  
  .draw-canvas {
    width: 100%;
    height: 300px;
  }
}
</style>
